<template>
	<view class="pet-home-container">
		<!-- 顶部搜索和消息区域 -->
		<view class="top-bar">
			<view class="search-container">
				<image src="/static/index/search-icon.png" mode="aspectFill"></image>
				<input type="text" v-model="searchKeyword" @confirm="handleSearch" placeholder="搜索宠物食品"
					class="search-input" />
			</view>
			<!-- <view class="message-icon">
				<text class="iconfont icon-message"></text>
				<view class="message-badge" v-if="unreadMessages > 0">
					{{ unreadMessages }}
				</view>
			</view> -->
		</view>

		<swiper class="brand-swiper" :indicator-dots="true" :autoplay="true" :interval="3000">
			<swiper-item v-for="(banner, index) in brandBanners" :key="index">
				<image :src="banner.image" class="brand-banner" mode="aspectFill"></image>
			</swiper-item>
		</swiper>
		<!-- 品牌推荐专区 -->
		<view class="brand-recommend">
			<view class="section-title">
				<text class="title-text">{{ isSearching ? '搜索结果' : '热销推荐' }}</text>
				<text class="more-link" v-if="isSearching" @click="resetSearch">返回推荐 ></text>
			</view>
			<view class="recommend-section">

				<view v-for="(product, index) in hotProducts" :key="index" class="product-item"
					@click="onProductDetail(product)">
					<image :src="product.image" class="product-image"></image>
					<text class="product-name">{{ product.name }}</text>
					<text class="product-price">¥{{ product.price }}</text>
				</view>
			</view>

			<view class="promotion-section">
				<view class="section-title">
					<text class="title-text">促销活动</text>
				</view>
				<view class="promotion-list">
					<view v-for="(promo, index) in promotions" :key="index" class="promotion-item" @click="goStore">
						<image :src="promo.image" mode="aspectFill" class="promo-image"></image>
						<view class="promo-info">
							<text class="promo-title">{{ promo.title }}</text>
							<text class="promo-desc">{{ promo.description }}</text>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 智能推送 -->
		<view class="smart-recommend">
			<view class="section-title">
				<text class="title-text">智能推荐</text>
				<text class="subtitle">根据小毛球的健康状况</text>
			</view>
			<view class="recommend-list">
				<view v-for="(item, index) in smartRecommends" :key="index" class="recommend-item"
					@click="onProductDetail(item)">
					<image :src="item.image" class="recommend-image"></image>
					<view class="recommend-info">
						<text class="recommend-name">{{ item.name }}</text>
						<text class="recommend-desc">{{ item.description }}</text>
						<text class="recommend-reason">推荐理由：{{ item.reason }}</text>
						<text class="recommend-price">¥{{ item.price }}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- AI问答 -->
		<view class="ai-assistant">
			<view class="section-title">
				<text class="title-text" @click="scrollToBottom">AI问答</text>
				<text class="subtitle">专业宠物健康助手</text>
			</view>
			<view class="chat-container">
				<scroll-view scroll-y class="chat-messages" :scroll-top="scrollTop">
					<view v-for="(msg, index) in chatMessages" :key="index" class="chat-message" :class="msg.type">
						<image :src="msg.avatar" class="chat-avatar"></image>
						<view class="message-content" :class="{'loading-message': msg.isLoading}">
							{{ msg.content }}
							<!-- <view v-if="msg.isLoading" class="loading-dots"></view> -->
						</view>
					</view>
				</scroll-view>
				<view class="chat-input-container">
					<input type="text" v-model="chatInput" placeholder="输入您的宠物健康问题" class="chat-input"
						@keypress="handleKeypress" />
					<button class="send-button" @click="sendMessage" :disabled="isLoading">
						{{ isLoading ? '发送中...' : '发送' }}
					</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		productApi,
		userApi
	} from '@/api/user.js'
	export default {
		data() {
			return {
				value: 0,
				unreadMessages: 3,
				brandBanners: [{
						image: '/static/index/about1.jpg'
					},
					{
						image: '/static/index/about2.jpg'
					}, {
						image: '/static/index/about4.jpg'
					}, {
						image: '/static/index/about5.jpg'
					}
				],
				hotProducts: [{
						id: 1,
						name: '高蛋白狗粮',
						price: 99.9,
						image: '/static/pet-test.png'
					},
					{
						id: 2,
						name: '全期犬粮',
						price: 129.9,
						image: '/static/pet-test.png'
					},
					{
						id: 3,
						name: '全期犬粮',
						price: 129.9,
						image: '/static/pet-test.png'
					}
				],
				promotions: [{
					title: '新品上市',
					description: '全系列5折优惠',
					image: '/static/index/xinpin.jpg'
				}],
				smartRecommends: [{
					id: 1,
					name: '钙质营养补充粉',
					description: '专为缺钙犬只定制',
					reason: '根据健康档案推荐',
					price: 49.9,
					image: '/static/pet-test.png'
				}],
				chatMessages: [{
					type: 'ai',
					avatar: '/static/index/ai.png',
					content: '您好！我是您的宠物健康助手，有什么可以帮您的吗？'
				}],
				chatInput: '',
				scrollTop: 0,
				isLoading: false, // 添加加载状态标识
				typingInterval: null, // 控制打字动画的计时器
				tempAiResponse: '', // 存储完整AI回复
				currentDisplayText: '', // 当前显示的文本
				searchKeyword: '', // 搜索关键词
				isSearching: false, // 是否正在搜索状态
				searchResults: [], // 搜索结果
				originalHotProducts: [], // 保存原始热销商品列表
				userAvatar: ''
			}
		},
		mounted() {
			this.originalHotProducts = [...this.hotProducts];
			this.fetchProducts()
			this.getUserInfo()
		},
		methods: {
			changeTab(e) {
				if (e == 0) {
					uni.navigateTo({
						url: '/pages/index/index'
					})
				} else if (e == 1) {
					uni.navigateTo({
						url: '/pages/shop/shop'
					})
				} else if (e == 2) {
					uni.navigateTo({
						url: '/pages/health/health'
					})
				} else if (e == 3) {
					uni.navigateTo({
						url: '/pages/forum/forum'
					})
				} else if (e == 4) {
					uni.navigateTo({
						url: '/pages/mine/mine'
					})
				}
			},
			// 获取商品列表
			async fetchProducts() {
				try {
					const result = await productApi.getProductList()
					console.log(result);
					// 检查结果是否有效

					// 筛选包含"热销"标签的商品
					let hotProducts = result.filter(product => {
						const tags = product.label ? product.label.split(' ') : [];
						return tags.includes('热销');
					});
					hotProducts = hotProducts.slice(0, 3);
					// 更新热销商品列表
					if (hotProducts.length > 0) {
						this.hotProducts = hotProducts.map(item => ({
							id: item.id,
							name: item.tradeName,
							price: item.prices,
							image: item.picture || '/static/pet-test.png' // 如果没有图片则使用默认图片
						}));

						// 同时更新原始热销商品列表(用于搜索重置)
						this.originalHotProducts = [...this.hotProducts];
					}

				} catch (error) {
					uni.showToast({
						title: '获取商品失败: ' + (error.message || '未知错误'),
						icon: 'none'
					});
					console.error('获取商品失败', error);
				}
			},
			// 搜索按钮点击处理
			handleSearch() {
				if (!this.searchKeyword.trim()) {
					// 如果搜索关键词为空，恢复原始商品显示
					this.resetSearch();
					return;
				}

				// 设置搜索状态
				this.isSearching = true;

				// 模拟搜索延迟
				uni.showLoading({
					title: '搜索中...'
				});

				setTimeout(() => {
					// 执行搜索逻辑
					this.performSearch();

					uni.hideLoading();
				}, 500); // 500ms延迟模拟搜索过程
			},

			// 执行搜索
			performSearch() {
				const keyword = this.searchKeyword.toLowerCase().trim();

				// 搜索所有可能包含商品的数组
				// 1. 热销商品
				const hotResults = this.originalHotProducts.filter(item =>
					item.name.toLowerCase().includes(keyword)
				);

				// 2. 促销活动（如果需要）
				const promoResults = this.promotions.filter(item =>
					item.title.toLowerCase().includes(keyword) ||
					item.description.toLowerCase().includes(keyword)
				);

				// 3. 智能推荐
				const recommendResults = this.smartRecommends.filter(item =>
					item.name.toLowerCase().includes(keyword) ||
					item.description.toLowerCase().includes(keyword)
				);

				// 合并搜索结果（移除重复项）
				this.searchResults = [
					...hotResults,
					...recommendResults
				];

				// 更新显示的商品为搜索结果
				this.hotProducts = this.searchResults;

				// 如果没有结果，显示提示
				if (this.searchResults.length === 0) {
					uni.showToast({
						title: '没有找到相关商品',
						icon: 'none'
					});
				} else {
					uni.showToast({
						title: `找到${this.searchResults.length}个相关商品`,
						icon: 'none'
					});

					// 滚动到热销推荐区域
					// this.scrollToHotProducts();
				}
			},

			// 重置搜索，恢复原始数据展示
			resetSearch() {
				this.isSearching = false;
				this.searchKeyword = '';
				this.searchResults = [];
				this.hotProducts = [...this.originalHotProducts];
			},

			// 搜索框回车键处理
			handleSearchKeypress(event) {
				if (event.keyCode === 13) {
					this.handleSearch();
				}
			},

			// // 滚动到热销商品区域
			// scrollToHotProducts() {
			// 	// 使用DOM选择器获取热销商品区域
			// 	setTimeout(() => {
			// 		const el = document.querySelector('.section-title:contains("热销推荐")');
			// 		if (el) {
			// 			el.scrollIntoView({
			// 				behavior: 'smooth',
			// 				block: 'start'
			// 			});
			// 		}
			// 	}, 300);
			// },
			onProductDetail(product) {
				// 跳转到商品详情页
				getApp().globalData.currentGoodId = product.id;
				uni.navigateTo({
					url: `/pages/shop/goods?id=${product.id}`
				})
			},
			goStore() {
				getApp().globalData.currentStored = 1;
				uni.navigateTo({
					url: '/pages/shop/store'
				})
			},
			// 逐字显示AI回答的函数
			typeMessage(fullText, messageIndex) {
				// 清除之前的计时器
				if (this.typingInterval) {
					clearInterval(this.typingInterval)
				}

				let i = 0
				this.chatMessages[messageIndex].content = ''
				// this.chatMessages[messageIndex].isAnimating = true

				// 确保视图先更新一次
				this.$nextTick(() => {
					// 使用setInterval逐字显示文本
					this.typingInterval = setInterval(() => {
						if (i < fullText.length) {
							// 添加一个字符
							this.chatMessages[messageIndex].content += fullText.charAt(i)
							i++
							// 保持滚动到底部
							this.scrollToBottom()
						} else {
							// 动画完成
							clearInterval(this.typingInterval)
							this.typingInterval = null
						}
					}, 40) // 每50毫秒显示一个字符
				})
			},
			// 在回复添加后调用
			scrollToBottom() {
				// 使用uni-app的页面滚动API
				uni.createSelectorQuery()
					.select('.chat-messages')
					.boundingClientRect(data => {
						if (data) {
							const query = uni.createSelectorQuery().in(this)
							query.selectAll('.chat-message').boundingClientRect(res => {
								let height = 0
								res.forEach(item => {
									height += item.height
								})
								this.scrollTop = height + 1000 // 加上额外高度确保滚动到底
							}).exec()
						}
					})
					.exec()
			},
			async getUserInfo() {
				try {
					const result = await userApi.getUserInfo()
					this.userAvatar = result.avatar
					console.log('获取用户信息成功：', this.userAvatar);
				} catch (error) {
					uni.showToast({
						title: '获取用户信息失败: ' + (error.message || '未知错误'),
						icon: 'none'
					});
					console.error('获取用户信息失败：', error);
				}
			},
			async sendMessage() {
				if (!this.chatInput.trim() || this.isLoading) return

				// 设置加载状态
				this.isLoading = true

				// 用户消息
				this.chatMessages.push({
					type: 'user',
					avatar: this.userAvatar,
					content: this.chatInput
				})

				// 保存用户输入并清空输入框
				const userQuestion = this.chatInput
				this.chatInput = ''

				// 添加一个带加载动画的AI消息占位
				const loadingMsgIndex = this.chatMessages.length
				this.chatMessages.push({
					type: 'ai',
					avatar: '/static/index/ai.png',
					content: '思考中',
					isLoading: true,
					isAnimating: false
				})
				// 启动加载动画
				let loadingDots = 0
				const loadingAnimation = setInterval(() => {
					loadingDots = (loadingDots + 1) % 4
					this.chatMessages[loadingMsgIndex].content = '思考中' + '.'.repeat(loadingDots)
				}, 300)
				try {
					// 准备请求数据
					const requestData = {
						model: "4.0Ultra",
						messages: [{
								role: "system",
								content: "你是一个专业的宠物健康顾问，请用中文回答用户关于宠物健康、饮食、护理等方面的问题。"
							},
							{
								role: "user",
								content: userQuestion
							}
						]
					}

					// 调用讯飞星火API
					const response = await uni.request({
						url: 'https://spark-api-open.xf-yun.com/v1/chat/completions',
						method: 'POST',
						data: requestData,
						header: {
							'Content-Type': 'application/json',
							'Authorization': 'Bearer EVLZswPnFzQiNzOkWgfy:kYipJGaozbPtsqTYNkAl'
						}
					})
					// 停止加载动画
					clearInterval(loadingAnimation)

					// 处理响应
					if (response.statusCode === 200 && response.data) {
						// 假设API返回的结构中包含回答文本
						let aiResponse = response.data.choices[0].message.content;

						// 更新消息对象
						this.$set(this.chatMessages, loadingMsgIndex, {
							type: 'ai',
							avatar: '/static/index/ai.png',
							content: '',
							isLoading: false
						})
						// 确保视图更新后再开始动画
						this.$nextTick(() => {
							this.typeMessage(aiResponse, loadingMsgIndex)
						})
					} else {
						// 添加错误信息
						const errorMsg = '抱歉，我暂时无法回答，请稍后再试。'
						this.chatMessages[loadingMsgIndex] = {
							type: 'ai',
							avatar: '/static/index/ai.png',
							content: '',
							isLoading: false,
							isAnimating: true
						}
						this.typeMessage(errorMsg, loadingMsgIndex)
					}
				} catch (error) {
					console.error('AI请求错误:', error)
					// 停止加载动画
					clearInterval(loadingAnimation)

					// 添加错误信息
					const errorMsg = '网络连接出现问题，请稍后再试。'
					this.chatMessages[loadingMsgIndex] = {
						type: 'ai',
						avatar: '/static/index/ai.png',
						content: '',
						isLoading: false,
						isAnimating: true
					}
					this.typeMessage(errorMsg, loadingMsgIndex)
				} finally {
					// 关闭加载状态
					this.isLoading = false
				}
			},
			// 可选：添加输入框回车发送功能
			handleKeypress(event) {
				if (event.keyCode === 13) {
					this.sendMessage()
				}
			}
		}
	}
</script>

<style scoped>
	.icon {
		width: 46rpx;
		height: 46rpx;
	}

	.pet-home-container {
		background-color: #f5f5f5;
		padding-bottom: 40rpx;
	}

	.top-bar {
		display: flex;
		align-items: center;
		padding: 0rpx 30rpx;
		background-color: #F9CB43;
		height: 170rpx;
	}

	.search-container {
		flex: 1;
		background-color: white;
		display: flex;
		align-items: center;
		border-radius: 40rpx;
		padding: 20rpx 20rpx;
		margin-top: 40rpx;
	}

	.search-container image {
		width: 50rpx;
		height: 50rpx;
	}

	.search-input {
		flex: 1;
		margin-left: 20rpx;
		font-size: 28rpx;
	}

	.message-icon {
		position: relative;
	}

	.message-badge {
		position: absolute;
		top: -10rpx;
		right: -10rpx;
		background-color: red;
		color: white;
		border-radius: 50%;
		width: 32rpx;
		height: 32rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 20rpx;
	}

	.brand-recommend {
		background-color: white;
		margin: 20rpx;
		border-radius: 20rpx;
		padding-bottom: 30rpx;
	}

	.brand-swiper {
		margin-bottom: 30rpx;
		height: 400rpx;
	}

	.brand-banner {
		width: 100%;
		height: 400rpx;
		border-radius: 0rpx 0rpx 10rpx 10rpx;
	}

	.title-text {
		font-size: 32rpx;
		font-weight: bold;
		position: relative;
		padding-left: 20rpx;
	}

	.title-text::before {
		content: '';
		position: absolute;
		left: 0;
		top: 10rpx;
		height: 30rpx;
		width: 8rpx;
		background-color: #F9CB43;
		border-radius: 4rpx;
	}

	.section-title {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 24rpx 30rpx;
		margin: 0;
		margin-bottom: 20rpx;
		font-size: 32rpx;
		font-weight: bold;
	}

	.more-link {
		color: #666;
		font-size: 24rpx;
	}

	.recommend-section {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
		padding: 0 30rpx;
	}

	.product-item {
		width: 32%;
		display: flex;
		flex-direction: column;
		margin-bottom: 30rpx;
		text-align: center;
	}

	.product-image {
		width: 100%;
		height: 240rpx;
		border-radius: 20rpx;
		margin-bottom: 16rpx;
	}

	.product-name {
		font-size: 28rpx;
		margin-bottom: 8rpx;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.product-price {
		color: #FF6B35;
		font-weight: bold;
		font-size: 28rpx;
	}

	.promotion-list {
		padding: 0 30rpx;
	}

	.promotion-item {
		display: flex;
		align-items: center;
		background-color: #f9f9f9;
		border-radius: 20rpx;
		margin-bottom: 20rpx;
		padding: 20rpx;
	}

	.promo-image {
		width: 160rpx;
		height: 160rpx;
		border-radius: 20rpx;
		margin-right: 30rpx;
	}

	.promo-info {
		flex: 1;
	}

	.promo-title {
		font-weight: bold;
		margin-bottom: 10rpx;
		display: block;
		font-size: 28rpx;
	}

	.promo-desc {
		color: #666;
		font-size: 24rpx;
	}

	.smart-recommend,
	.ai-assistant {
		background-color: white;
		margin: 20rpx;
		border-radius: 20rpx;
		padding-bottom: 30rpx;
	}

	.subtitle {
		color: #666;
		font-size: 24rpx;
		margin-left: 20rpx;
		padding: 24rpx 30rpx;
		margin: 0;
	}

	.recommend-list {
		padding: 0 30rpx;
	}

	.recommend-item {
		display: flex;
		align-items: center;
		margin-bottom: 30rpx;
		background-color: #f9f9f9;
		border-radius: 20rpx;
		padding: 20rpx;
	}

	.recommend-image {
		width: 200rpx;
		height: 200rpx;
		border-radius: 20rpx;
		margin-right: 30rpx;
		object-fit: cover;
	}

	.recommend-info {
		flex: 1;
		display: flex;
		flex-direction: column;
	}

	.recommend-name {
		font-weight: bold;
		margin-bottom: 10rpx;
		font-size: 28rpx;
	}

	.recommend-desc {
		color: #666;
		font-size: 24rpx;
		margin-bottom: 10rpx;
	}

	.recommend-reason {
		color: #F9CB43;
		font-size: 24rpx;
		margin: 10rpx 0;
	}

	.recommend-price {
		color: #FF6B35;
		font-weight: bold;
		margin-top: 10rpx;
		font-size: 28rpx;
	}

	.chat-container {
		padding: 0 30rpx;
	}

	.chat-messages {
		height: 600rpx;
		background-color: #f9f9f9;
		border-radius: 20rpx;
		padding: 20rpx 0;
		margin-bottom: 20rpx;
	}

	.chat-message {
		display: flex;
		margin-bottom: 30rpx;
	}

	.chat-message.ai {
		flex-direction: row;
	}

	.chat-message.user {
		flex-direction: row-reverse;
	}

	.chat-avatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		margin: 0 20rpx;
	}

	.message-content {
		padding: 24rpx;
		border-radius: 30rpx;
		max-width: 70%;
		word-break: break-word;
		font-size: 28rpx;
	}

	.chat-message.user .message-content {
		background-color: #F9CB43;
		color: #fff;
	}

	.chat-message.ai .message-content {
		background-color: #f0f0f0;
	}

	.chat-input-container {
		display: flex;
		align-items: center;
		margin-top: 20rpx;
	}

	.chat-input {
		flex: 1;
		background-color: #f9f9f9;
		border-radius: 40rpx;
		padding: 20rpx;
		margin-right: 20rpx;
		height: 80rpx;
		font-size: 28rpx;
	}

	.send-button {
		background-color: #F9CB43;
		color: white;
		border-radius: 40rpx;
		padding: 0 40rpx;
		height: 80rpx;
		line-height: 80rpx;
		font-size: 28rpx;
	}

	/* 响应式优化 */
	@media screen and (min-width: 768rpx) {
		.product-item {
			width: 32%;
			/* 大屏幕上显示三列 */
		}

		.recommend-item {
			width: 48%;
			display: inline-flex;
			margin-right: 2%;
		}
	}

	/* 添加到现有的CSS样式中 */
	.loading-message {
		position: relative;
	}

	.loading-dots {
		position: absolute;
		bottom: 5rpx;
		right: 10rpx;
		width: 40rpx;
		height: 20rpx;
		background-image: linear-gradient(to right, #F9CB43 0%, #F9CB43 33%, transparent 33%, transparent 66%, #F9CB43 66%, #F9CB43 100%);
		background-size: 300% 100%;
		animation: loading 1s infinite linear;
	}

	@keyframes loading {
		0% {
			background-position: 0% 0;
		}

		100% {
			background-position: 100% 0;
		}
	}

	.chat-message.ai .message-content.typing::after {
		content: '|';
		display: inline-block;
		animation: cursor-blink 1s infinite;
	}

	@keyframes cursor-blink {

		0%,
		100% {
			opacity: 1;
		}

		50% {
			opacity: 0;
		}
	}
</style>